<template>
  <el-dialog
    @close="cancel"
    :title="title"
    :visible.sync="open"
    width="760px"
    class="dialogClass"
    append-to-body
  >
    <template slot="title">
      <div class="modalTitle">
        <img
          src="@/assets/bluelogo/drawerTitle.png"
          alt=""
          class="titleLogo"
        />{{ title }}
      </div>
    </template>
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      size="small"
      label-width="140px"
    >
      <el-form-item label="案件名称:" prop="caseId">
        <el-select
          v-model.trim="formData.caseId"
          filterable
          placeholder="请选择案件名称"
          clearable
          class="caseSelect"
        >
          <el-option
            v-for="item in cases"
            :key="item.id"
            :label="item.caseName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人员姓名" prop="applicationName">
            <el-input
              v-model.trim="formData.applicationName"
              placeholder="请输入申请人员姓名"
              :maxlength="50"
              clearable
            ></el-input> </el-form-item></el-col
        ><el-col :span="12">
          <el-form-item label="申请人联系方式" prop="applicationTel">
            <el-input
              v-model.trim="formData.applicationTel"
              placeholder="请输入申请人联系方式"
              :maxlength="50"
              clearable
            >
            </el-input> </el-form-item></el-col
      ></el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人员身份证号" prop="applicationZjh">
            <el-input
              v-model.trim="formData.applicationZjh"
              placeholder="请输入申请人员身份证号"
              :maxlength="50"
              clearable
            ></el-input> </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="与涉案人关系" prop="applicationRelation">
            <el-select
              class="selectClass"
              v-model="formData.applicationRelation"
              placeholder="请选择与涉案人关系"
              clearable=""
            >
              <el-option
                v-for="item in dict.type.relation_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select> </el-form-item
        ></el-col></el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="涉案人员姓名" prop="name">
            <el-input
              v-model.trim="formData.name"
              placeholder="请输入涉案人员姓名"
              :maxlength="50"
              clearable
            ></el-input> </el-form-item></el-col
        ><el-col :span="12">
          <el-form-item label="涉案人联系方式" prop="tel">
            <el-input
              v-model.trim="formData.tel"
              placeholder="请输入涉案人联系方式"
              :maxlength="50"
              clearable
            >
            </el-input> </el-form-item></el-col
      ></el-row>
      <!-- <el-row></el-row> -->
      <el-form-item label="涉案人身份证号" prop="zjh">
        <el-input
          v-model.trim="formData.zjh"
          placeholder="请输入涉案人身份证号"
          :maxlength="50"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item label="涉案人户籍地址" prop="residenceAddress">
        <el-input
          v-model.trim="formData.residenceAddress"
          placeholder="请输入涉案人户籍地址"
          :maxlength="50"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item label="涉案人居住地所属区域"  :required="true" >
        <el-row :gutter="24" class="oucodeList">
                <el-col :span="7">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="oucodeList[0]"
                  >
                    <DictionarySelect
                    class="dicSelect"
                      placeholder="请选择省"
                      source="xzqhbm"
                      v-model="formData.oucodeList[0]"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="oucodeList[1]"
                  >
                    <DictionarySelect
                      placeholder="请选择市"
                      :source="formData.oucodeList[0]"
                      v-model="formData.oucodeList[1]"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="oucodeList[2]"
                  >
                    <DictionarySelect
                      placeholder="请选择区县"
                      :source="formData.oucodeList[1]"
                      v-model="formData.oucodeList[2]"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
      </el-form-item>
      <el-form-item label="涉案人居住地址" prop="liveAddress">
        <el-input
          v-model.trim="formData.liveAddress"
          placeholder="请输入涉案人居住地址"
          :maxlength="50"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="判决损失金额(元)"
            prop="personJudgmentLossAmount"
          >
            <el-input
              oninput="value=value.replace(/[^0-9.]/g,'')"
              v-model="formData.personJudgmentLossAmount"
              placeholder="请选择判决损失金额"
              :maxlength="15"
            >
            </el-input> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item
            label="认定发放金额(元)"
            prop="personConfirmedPaymentAmount"
          >
            <el-input
              oninput="value=value.replace(/[^0-9.]/g,'')"
              v-model.trim="formData.personConfirmedPaymentAmount"
              placeholder="请输入认定发放金额"
              :maxlength="15"
              clearable
            >
            </el-input> </el-form-item
        ></el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="收款方式" prop="collectionWay">
            <el-select
              class="selectClass"
              v-model="formData.collectionWay"
              placeholder="请选择收款方式"
              clearable=""
            >
              <el-option
                v-for="item in dict.type.collection_way"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="收款账号" prop="collectionNumber">
            <el-input
              v-model="formData.collectionNumber"
              placeholder="请输入收款账号"
              :maxlength="30"
            >
            </el-input> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <div class="dialog-footer">
        <el-button @click="cancel" class="resetButton">取消</el-button>
        <el-button class="searchButton" @click="submitForm">确定</el-button>
        <el-button
          class="saveButton"
          v-show="!saveNew"
          @click.native="handleAllAdd"
        >
          保存并新建</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { MODALTYPE, MODALIMG, CASEDEFAULTSTATE } from "../../../utils/variable";
import { onlyNumber } from "../../../utils/commonMethods";
import DictionarySelect from "../../../layout/components/dictionnary/DictionarySelect.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getCase,
  getTree,
  validNumber,
  updateCase,
  getCaseList,
} from "@/api/caseManage/case";
import {
  addConfirmPeople,
  getDetail,
  editCasePerson,
  judgmentDup,
  judgmentLoss,
  judgmentConfirmed,
} from "@/api/peopleConfirm/peopleConfirm";
export default {
  dicts: ["collection_way", "relation_type"],
  inheritAttrs: false,
  components: { Treeselect, DictionarySelect },
  props: {
    modalType: {
      type: String,
      require: true,
    },
    id: {
      type: Number,
    },
  },
  data() {
    //案件重复校验
    var checkRulingBookNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error("身份证号不能为空"));
      } else if (this.modalType == MODALTYPE["新增"]) {
        const reg =
          /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
        const card = reg.test(value);
        if (!card) {
          callback(new Error("身份证号格式错误！"));
        } else {
          let params = {
            caseId: this.formData.caseId,
            zjh: this.formData.zjh,
          };
          judgmentDup(params.zjh, params.caseId).then((response) => {
            console.log(response);
            if (response === false) {
              callback(new Error("该人员案款确认信息已存在！"));
            } else {
              callback();
            }
          });
        }
      } else if (this.modalType == MODALTYPE["修改"]) {
        const reg =
          /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
        const card = reg.test(value);
        if (!card) {
          callback(new Error("身份证号格式错误！"));
        } else {
          if (
            this.temCaseId !== this.formData.caseId &&
            this.temZjh !== value
          ) {
            let params = {
              caseId: this.formData.caseId,
              zjh: value,
            };
            judgmentDup(params.caseId, params.zjh).then((response) => {
              if (response.data === 1) {
                callback(new Error("该人员案款确认信息已存在！"));
              } else {
                callback();
              }
            });
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    //损失金额重复校验
    var checkMoneyNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error("判决损失金额不能为空"));
      } else if (this.modalType == MODALTYPE["新增"]) {
        let params = {
          money: this.formData.personJudgmentLossAmount,
          caseId: this.formData.caseId,
        };
        judgmentLoss(params.money, params.caseId).then((response) => {
          if (response.flag === false) {
            callback(
              new Error(
                "损失金额已超过案件剩余损失金额!剩余损失金额为" +
                  response.remainAmount +
                  "元！"
              )
            );
          } else {
            callback();
          }
        });
      } else if (this.modalType == MODALTYPE["修改"]) {
        if (
          this.tmpMoney !== this.formData.personJudgmentLossAmount ||
          this.temCaseId !== this.formData.caseId
        ) {
          let params = {
            money: this.formData.personJudgmentLossAmount - this.tmpMoney,
            caseId: this.formData.caseId,
          };
          judgmentLoss(params.money, params.caseId).then((response) => {
            if (response.flag === false) {
              callback(new Error("损失金额已超过案件剩余损失金额!"));
            } else {
              callback();
            }
          });
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //认定金额重复校验
    var checkConfirmMoneyNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error("认定金额不能为空"));
      } else if (this.modalType == MODALTYPE["新增"]) {
        let params = {
          money: this.formData.personConfirmedPaymentAmount,
          caseId: this.formData.caseId,
        };
        judgmentConfirmed(params.money, params.caseId).then((response) => {
          if (response.flag === false) {
            callback(
              new Error(
                "认定金额已超过案件剩余认定金额！剩余认定金额为" +
                  response.remainAmount +
                  "元！"
              )
            );
          } else {
            callback();
          }
        });
      } else if (this.modalType == MODALTYPE["修改"]) {
        if (
          this.tmpConfirmMoney !== this.formData.personConfirmedPaymentAmount ||
          this.temCaseId !== this.formData.caseId
        ) {
          let params = {
            money:
              this.formData.personConfirmedPaymentAmount - this.tmpConfirmMoney,
            caseId: this.formData.caseId,
          };
          judgmentConfirmed(params.money, params.caseId).then((response) => {
            if (response.flag === false) {
              callback(new Error("损失金额已超过案件剩余损失金额!"));
            } else {
              callback();
            }
          });
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      saveNew: false,
      isDisabled: false,
      // 弹出层标题
      title: "",
      temCaseName: "",
      temRulingBookNumber: "",
      // 部门树选项
      deptOptions: [],
      // 是否显示弹出层
      open: false,
      cases: [],
      temZjh: "",
      temCaseId: "",
      tmpConfirmMoney: "",
      tmpMoney: "",
      formData: {
        caseId: "",
        caseName: "",
        name: "",
        zjh: "",
        residenceAddress: "", //户籍地址
        liveAddress: "", //居住地址
        tel: "", //联系方式
        oucodeList: ["", "", ""],
        personJudgmentLossAmount: "", //判决损失金额
        personConfirmedPaymentAmount: "", //认定发放金额
        collectionWay: "", //收款方式
        collectionNumber: "",
        applicationName: "",
        applicationTel: "",
        applicationZjh: "",
        applicationRelation: "",
      },
      rules: {
        tel: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        liveAddress: [
          {
            required: true,
            message: "请输入居住地址",
            trigger: "blur",
          },
        ],
        "oucodeList[0]": [
          {
            required: true,
            message: "请选择所属省",
            trigger: "change",
          },
        ],
        "oucodeList[1]": [
          {
            required: true,
            message: "请选择所属市",
            trigger: "change",
          },
        ],
        "oucodeList[2]": [
          {
            required: true,
            message: "请选择所属区县",
            trigger: "change",
          },
        ],
        caseId: [
          {
            required: true,
            message: "请输入案件名称",
            trigger: "change",
          },
        ],
        // caseName: [
        //   {
        //     required: true,
        //     message: "请输入案件名称",
        //     trigger: "blur",
        //   },
        // ],
        name: [
          {
            required: true,
            // validator: checkRulingBookNumber,
            message: "请输入涉案人员姓名",
            trigger: "blur",
          },
        ],
        zjh: [
          {
            required: true,
            validator: checkRulingBookNumber,
            trigger: "blur",
          },
        ],
        collectionWay: [
          {
            required: false,
            message: "请选择收款方式",
            trigger: "change",
          },
        ],
        personJudgmentLossAmount: [
          {
            required: true,
            // validator: checkMoneyNumber,
            message: "请输入判决损失金额（元）",
            trigger: "blur",
          },
        ],
        personConfirmedPaymentAmount: [
          {
            required: false,
            // validator: checkConfirmMoneyNumber,
            message: "请输入认定发放金额（元）",
            trigger: "blur",
          },
        ],
        collectionNumber: [
          {
            required: false,
            message: "请输入收款账号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    resetButtonContent() {
      if (this.modalType == MODALTYPE["详情"]) {
        return "关闭";
      } else {
        return "取消";
      }
    },
  },
  watch: {
    modalType: {
      handler(value) {
        if (value == MODALTYPE["新增"]) {
          this.reset();
          this.getCases();
          this.open = true;
          this.title = "新增已确认信息";
        } else if (value == MODALTYPE["修改"]) {
          this.saveNew = true;
          this.reset();
          this.getCases();
          if (this.id) {
            getDetail(this.id).then((response) => {
              if(response.data.tinvolvedPersonVO.oucodeList){ 
                 this.formData.oucodeList = response.data.tinvolvedPersonVO.oucodeList;
                }

              this.formData.caseId = response.data.tcasePerson.caseId;
              this.formData.collectionNumber =
                response.data.tcasePerson.collectionNumber;
              this.formData.name = response.data.tinvolvedPersonVO.name;
              this.formData.zjh = response.data.tinvolvedPersonVO.zjh;
              this.formData.tel = response.data.tinvolvedPersonVO.tel;
              this.formData.residenceAddress =
                response.data.tinvolvedPersonVO.residenceAddress;
              this.formData.liveAddress =
                response.data.tinvolvedPersonVO.liveAddress;
              this.formData.personJudgmentLossAmount =
                response.data.tcasePerson.personJudgmentLossAmount;
              this.formData.personConfirmedPaymentAmount =
                response.data.tcasePerson.personConfirmedPaymentAmount;
              this.formData.collectionWay =
                response.data.tcasePerson.collectionWay;
              this.temCaseId = response.data.tcasePerson.caseId;
              this.temZjh = response.data.tinvolvedPersonVO.zjh;
              this.tmpMoney = this.formData.personJudgmentLossAmount;
              this.tmpConfirmMoney = this.formData.personConfirmedPaymentAmount;
              this.open = true;
              this.title = "修改已确认信息";
            });
          }
        } else if (value == "detail") {
          this.isDisabled = true;
          this.reset();
          if (this.id) {
            getCase(this.id).then((response) => {
              this.formData = response.data;
              this.open = true;
              this.title = "已确认信息详情";
            });
          }
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    onlyNumber,
    getCases() {
      let params = {
        oucode: this.$store.state.user.oucode,
      };
      getCaseList(params).then((response) => {
        this.cases = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.$emit("update:modalType", "");
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.formData = {
        caseId: "",
        caseName: "",
        name: "",
        zjh: "",
        residenceAddress: "",
        liveAddress: "", //居住地址
        oucodeList: ["", "", ""],
        tel: "", //联系方式
        personJudgmentLossAmount: "",
        personConfirmedPaymentAmount: "", //认定发放金额
        collectionWay: "", //收款方式
        payedMoney: "",
        collectionNumber: "",
      };
      this.resetForm("form");
    },
    handleAllAdd() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.modalType == MODALTYPE["新增"]) {
            let params = {
              caseId: this.formData.caseId,
              involvedPersonDTO: this.formData,
            };
            addConfirmPeople(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = true;
              this.reset();
              // TODO：不要用这种方式访问父组件
              // this.$parent.getList();
              this.$emit("fatherMethod");
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.modalType == MODALTYPE["修改"]) {
            let params = {
              id: this.id,
              caseId: this.formData.caseId,
              involvedPersonDTO: this.formData,
            };
            editCasePerson(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit("update:modalType", "");
              // this.$parent.getList();
              this.$emit("fatherMethod");
            });
          } else if (this.modalType == MODALTYPE["新增"]) {
            let params = {
              caseId: this.formData.caseId,
              involvedPersonDTO: this.formData,
            };
            addConfirmPeople(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit("update:modalType", "");
              // TODO：不要用这种方式访问父组件
              // this.$parent.getList();
              this.$emit("fatherMethod");
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../assets/styles/dialog.scss"; //模态框样式

::v-deep.treeselect {
  font-size: 12px !important;
  font-family: $font-family !important;
  font-weight: $form-label-font-weight !important;
}
.saveButton {
  border: 1px solid $form-button-background-color;
  height: 38px;
  margin-left: -1px;
  width: 125px;
  border-radius: 2px;
  margin-right: 10px;
  font-size: $form-button-font-size;
  font-family: $font-family;
  font-weight: $form-button-font-weight;
  letter-spacing: 0;
  background-color: #598af9;
  color: #fff;
  line-height: 10px;
  letter-spacing: 0px;
}
.caseSelect {
  width: 100%;
}
.dialogClass {
  ::v-deep .el-dialog {
    top: 40px;
  }
}
.oucodeList {
  ::v-deep .el-form-item {
    margin: 0 !important;
  }
}
.dicSelect{
  width: 150px !important;
  margin-left: -10px !important;
}
</style>
